package com.ekuaitu.kuaitu.utils;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import com.ekuaitu.kuaitu.BuildConfig;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.activity.MainActivity;
import com.ekuaitu.kuaitu.receiver.NotificationClickReceiver;
import com.ekuaitu.kuaitu.widget.NumberProgressBar;

import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static android.content.Context.DOWNLOAD_SERVICE;

/**
 * Created by user1 on 2017/4/26.
 */
public class UpdateManager {

    public static final int SHOW_NOTIFICATION_DOWNLOADING = 0;
    public static final int SHOW_PROGRESS_DIALOG = 1;
    public static final int SHOW_NOTIFICATION_DONE = 2;
    private int UiType;
    private long downloadId;
    private DownloadManager manager;
    private Context mContext;
    private String apkName;
    private NumberProgressBar numberProgressBar;
    private ScheduledExecutorService scheduledExecutorService;
    private DownloadChangeObserver downloadObserver;

    public UpdateManager(Context mContext) {
        this.mContext = mContext;
        manager = (DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE);
    }

    /**
     * @param downloadUrl 下载地址
     * @param apkName     文件名
     * @param UiType      1显示Notification 2显示ProgressDialog
     */
    public void downLoadApk(String downloadUrl, String apkName, int UiType) {
        this.UiType = UiType;
        //创建下载请求
        DownloadManager.Request down = new DownloadManager.Request(Uri.parse(downloadUrl));
        //设置允许使用的网络类型
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        //载的文件可以被系统的Downloads应用扫描到并管理
        down.setVisibleInDownloadsUi(false);
        //设置下载标题
        down.setTitle("快兔出行");
        mContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        //显示Notification
        if (UiType == SHOW_NOTIFICATION_DOWNLOADING) {
            //推荐更新，非WiFi下，显示通知栏下载进度
            down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
            //设置下载后文件存放的位置，在SDCard/Download目录下面
            down.setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, apkName);
            //将下载请求放入队列,返回值为downloadId
            downloadId = manager.enqueue(down);
        } else if (UiType == SHOW_NOTIFICATION_DONE) {
            //推荐更新，wifi下，不显示通知栏下载进度，下载完成后弹出通知
            down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
            //设置下载后文件存放的位置，在SDCard/Download目录下面
            down.setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, apkName);
            //将下载请求放入队列,返回值为downloadId
            downloadId = manager.enqueue(down);
        } else if (UiType == SHOW_PROGRESS_DIALOG) {
            //强制更新，仅显示下载进度对话框
            down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
            //设置下载后文件存放的位置，在SDCard/Download目录下面
            down.setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, apkName);
            //将下载请求放入队列,返回值为downloadId
            downloadId = manager.enqueue(down);
            SharedPreferencesUtils.getInstance(mContext).putLongValue("downloadId", downloadId);
            registerContentObserver();
            initProgressDialog();
        }
    }

    /**
     * 注册ContentObserver
     */
    private void registerContentObserver() {
        /** observer download change **/
        downloadObserver = new DownloadChangeObserver(null);
        if (downloadObserver != null) {
            mContext.getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true, downloadObserver);
        }
    }

    public Handler downLoadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            numberProgressBar.setProgress(msg.what);
        }
    };

    class DownloadChangeObserver extends ContentObserver {

        public DownloadChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            Log.i("downrate", getBytesAndStatus() + "");
            downLoadHandler.sendMessage(downLoadHandler.obtainMessage(getBytesAndStatus()));

        }

    }

    private int getBytesAndStatus() {
        int[] bytesAndStatus = new int[]{
                -1, -1, 0
        };
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor cursor = null;
        try {
            cursor = manager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                //已经下载文件大小
                bytesAndStatus[0] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //下载文件的总大小
                bytesAndStatus[1] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                //下载状态
                bytesAndStatus[2] = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return bytesAndStatus[1] == 0 ? 0 : (int) (bytesAndStatus[0] / (float) bytesAndStatus[1] * 100);
    }

    private AlertDialog.Builder dialog;
    private AlertDialog alertDialog;

    private void initProgressDialog() {
        dialog = new AlertDialog.Builder(mContext);
        dialog.setIcon(R.mipmap.ic_launcher);
        dialog.setTitle("下载中...");
        //填充自定义Dialog的布局文件
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_download, null);
        //对Dialog自定义布局上的ui控件初始化
        numberProgressBar = (NumberProgressBar) view.findViewById(R.id.number_bar);
        dialog.setView(view);
        numberProgressBar.setProgress(0);
        dialog.setCancelable(false);
        alertDialog = dialog.show();

    }


    private BroadcastReceiver receiver = new BroadcastReceiver() {
        private DownloadManager manager;

        @Override
        public void onReceive(final Context context, Intent intent) {
            manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                Cursor myDownload = manager.query(query);
                if (myDownload.moveToFirst()) {
                    int fileNameIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
                    final String filePath = myDownload.getString(fileNameIdx);
                    createNotification(context, filePath);

                    if (alertDialog != null) {
                        alertDialog.dismiss();
                    }

                    if (UiType == UpdateManager.SHOW_NOTIFICATION_DOWNLOADING || UiType == UpdateManager.SHOW_NOTIFICATION_DONE) {
                    } else {
                        File apkfile = new File(filePath);
                        if (apkfile.exists()) {
                            Intent intent1 = new Intent(Intent.ACTION_VIEW);
                            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            Uri apkFileUri = Uri.fromFile(apkfile);
                            intent1.setDataAndType(apkFileUri, "application/vnd.android.package-archive");
                            mContext.startActivity(intent1);
                            SharedPreferencesUtils.getInstance(mContext).removeValue("downloadId");
                        }
                    }
                    if (UiType == SHOW_PROGRESS_DIALOG) {
                        AppManager.getAppManager().AppExit(mContext);
                    }
                }
            }

        }

        private void createNotification(Context context, String filePath) {
            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            Intent clickIntent = new Intent(context, NotificationClickReceiver.class);
            clickIntent.putExtra("filePath", filePath);
            PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, clickIntent, PendingIntent.FLAG_ONE_SHOT);
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setContentTitle("快兔出行");
            builder.setPriority(Notification.PRIORITY_MAX);
            builder.setTicker("快兔出行发现新版本啦");
            if (UiType == UpdateManager.SHOW_NOTIFICATION_DONE) {
                builder.setContentText("新版本已在WiFi下为您下载好，点击安装吧！");
            } else if (UiType == UpdateManager.SHOW_NOTIFICATION_DOWNLOADING) {
                builder.setContentText("新版本已为您下载好，点击安装吧！");
            }

            builder.setContentIntent(pIntent);
            builder.setDefaults(Notification.DEFAULT_ALL);
            builder.setAutoCancel(true);
            manager.notify(0, builder.build());
        }
    };
}
